package com.yuanrui.wechat.handler;

import com.yuanrui.wechat.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 文本消息处理器
 */
@Slf4j
@Component
public class ReceiveTextMsgHandler implements WechatMsgHandler {

    private static final String VERIFY_CODE = "验证码";

    private static final String LOGIN_PREFIX = "loginCode";

    private final RedisUtil redisUtil;

    public ReceiveTextMsgHandler(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    @Override
    public WechatMsgTypeEnum getMsgType() {
        return WechatMsgTypeEnum.TEXT;
    }

    @Override
    public String dealMsg(Map<String, String> messageMap) {
        log.info("接收到的文本消息为");
        String content = messageMap.get("Content");
        if (!VERIFY_CODE.equals(content)) {
            return null;
        }
        String fromUserName = messageMap.get("FromUserName");
        String toUserName = messageMap.get("ToUserName");
        //生成随机四位验证码
        String verifyCode = String.valueOf((int) ((Math.random() * 9 + 1) * 1000));
        String verifyCodeKey = redisUtil.buildKey(LOGIN_PREFIX, verifyCode);
        //将验证码存入redis,并设置过期时间为5分钟
        redisUtil.setNx(verifyCodeKey, fromUserName, 5L, TimeUnit.MINUTES);
        String replyContent = "您的验证码为：" + verifyCode + "五分钟内有效";
        return "<xml>\n" +
                "  <ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>\n" +
                "  <FromUserName><![CDATA[" + toUserName + "]]></FromUserName>\n" +
                "  <CreateTime>12345678</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA[" + replyContent + "]]></Content>\n" +
                "</xml>";
    }
}
